package com.redislock.aop.tool.util;

import org.assertj.core.util.Lists;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.concurrent.TimeUnit;

public class RedisUtil {
    private static RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    public static void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }


    public static boolean setnx(String key,Object value,Long time,TimeUnit timeUnit){
       return redisTemplate.opsForValue().setIfAbsent(key,value,time, timeUnit);
    }

    public static Boolean expire(String key,Long time,TimeUnit timeUnit ){
        return redisTemplate.expire(key,time,timeUnit);
    }

    public static boolean del(String key){
       return redisTemplate.delete(key);
    }

    public static Object script(String key,Object value){
        String script="if redis.call('get',KEYS[1])==ARGV[1] then\n" +
                " return redis.call('del',KEYS[1])\n" +
                " else\n" +
                " return 0\n" +
                " end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        //返回类型是Long
        redisScript.setResultType(Long.class);
        redisScript.setScriptText(script);
        Object result = redisTemplate.execute(redisScript, Lists.newArrayList(key),value);
        return result;
    }

    public static Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }
}
